package MovieFinderApp.MCXMLMovieFinder;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import MovieFinderApp.LCMovieInterfaces.*;
import MovieFinderApp.MCMovieFinderInterfaces.*;


public class XMLMovieFinder implements IMovieFinder, ICustomizeMovieFinder{
    
	private String filename;
	
	public XMLMovieFinder() {

	}
	
	public void setFilename(String filename){
		this.filename = filename;
	}

	public ArrayList<IMovie> findAll(){
		ArrayList<IMovie> list = new ArrayList<IMovie>();
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
	    DocumentBuilder builder = null;
	    Document document = null;
	    
		try {
			
			builder  = factory.newDocumentBuilder();
			document = builder.parse( new File(this.filename) );
			
			NodeList nl_movie = document.getElementsByTagName("movie");
			for(int i=0; i<nl_movie.getLength(); i++){
                ApplicationContext appCon = new FileSystemXmlApplicationContext("classpath:MovieFinderApp/MCXMLMovieFinder/properties/config.xml");
                IMovie movie = (IMovie)appCon.getBean("myMovie");
				NodeList nl_childs = nl_movie.item(i).getChildNodes();
				for(int j=0; j<nl_childs.getLength(); j++){
					if(nl_childs.item(j).getNodeName().equalsIgnoreCase("director")){
						movie.setDirector(nl_childs.item(j).getTextContent());
					}
					else if(nl_childs.item(j).getNodeName().equalsIgnoreCase("title")){
						movie.setTitle(nl_childs.item(j).getTextContent());
					}
				}
				
				list.add(movie);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
		    e.printStackTrace();
		}

		return list;
	}
}
